<template>
    <div>
        <el-dialog :title="isAdd ? '添加商品' : '修改商品'" :visible.sync="zhe" :before-close="close" @opened="createEdit">
            <el-form ref="form" :model="form" label-width="5rem" :rules="rules">

                <el-form-item label="一级分类" prop="first_cateid">
                    <el-select v-model="form.first_cateid" placeholder="请选择" @change="change1(true)">
                        <el-option v-for="item in catelist" :key="item.id" :label="item.catename"
                            :value="item.id"></el-option>

                    </el-select>
                </el-form-item>

                <el-form-item label="二级分类" prop="second_cateid">
                    <el-select v-model="form.second_cateid" placeholder="请选择">
                        <el-option v-for="item in cateArr" :key="item.id" :label="item.catename"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="商品名称" prop="goodsname">
                    <el-input v-model="form.goodsname"></el-input>
                </el-form-item>

                <el-form-item label="价格" prop="price">
                    <el-input v-model="form.price"></el-input>
                </el-form-item>

                <el-form-item label="市场价格" prop="market_price">
                    <el-input v-model="form.market_price"></el-input>
                </el-form-item>

                <el-form-item label="图片">
                    <el-upload action="#" list-type="picture-card" :file-list="photo" :auto-upload="false"
                        :on-preview="onPreview" :on-change="changeInfo" :limit="1">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>

                <el-form-item label="商品规格" prop="specsid">
                    <el-select v-model="form.specsid" placeholder="请选择" @change="change2(true)">
                        <el-option v-for="item in specslist" :key="item.id" :label="item.specsname"
                            :value="item.id"></el-option>

                    </el-select>
                </el-form-item>

                <el-form-item label="规格属性" prop="specsattr">
                    <el-select v-model="form.specsattr" placeholder="请选择" multiple>
                        <el-option v-for="item in specsArr" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="是否新品">
                    <el-radio-group v-model="form.isnew">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="2">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="是否热卖">
                    <el-radio-group v-model="form.ishot">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="2">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="状态">
                    <el-switch v-model="form.status" :active-value="1" :inactive-value="2"></el-switch>
                </el-form-item>

                <el-form-item label="商品描述" id="edit">

                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submit">确定</el-button>
                    <el-button @click="close">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
//引入符文本编辑
import E from 'wangeditor'
import { goodsadd, goodsinfo, goodsedit, specslist } from "../../request/api"
import { mapGetters, mapActions } from 'vuex';
export default {
    props: ["zhe", "isAdd"],
    data() {
        return {
            form: {
                first_cateid: "",//一级分类编号
                second_cateid: "",//二级分类编号
                goodsname: "",//商品名称
                price: "",//商品价格
                market_price: "",//市场价格
                img: [],//商品图片（文件）
                description: "",//商品描述
                specsid: "",//商品规格编号
                specsattr: "",//商品规格属性
                isnew: 1,//是否新品 1-是 2-否
                ishot: 1,//是否热卖推荐 1-是 2-否
                status: 1,//状态1正常2禁用

            },
            dialogImageUrl: '',
            dialogVisible: false,
            photo: [],
            // 正则验证
            rules: {
                price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
                market_price: [
                    { required: true, message: "请输入市场价格", trigger: "blur" },
                ],
                first_cateid: [
                    { required: true, message: "请选择一级分类", trigger: "change" },
                ],
                second_cateid: [
                    { required: true, message: "请选择二级分类", trigger: "blur" },
                ],
                specsid: [
                    { required: true, message: "请选择商品规格", trigger: "change" },
                ],
                specsattr: [
                    { required: true, message: "请选择规格属性", trigger: "blur" },
                ],
            },
            cateArr: [], //二级分类
            specsArr: [], //规格属性
            specslist: []//规格名称

        }
    },
    methods: {
        ...mapActions({
            getCateList: "cate/getCateListAction",
            getSpecsList: "specs/getSpecsListAction",
            getCount:"manage/getCountAction",
            getGoodsList: "manage/getGoodsInfoActions"

        }),
        //封装一个创建富文本的事件
        createEdit() {
            //组件一加载就创建富文本
            this.edit = new E("#edit");
            //创建
            this.edit.create()
            //初始化
            this.edit.txt.html(this.form.description)
            // console.log(this.edit, "富文本对象");
        },
        // 监听上传图片
        changeInfo(file) {
            this.form.img = file.raw
        },
        //图片预览
        onPreview(file) {
            // console.log(file, '文件的内容')
            //打开预览弹框
            this.dialogVisible = true
            // 给弹框赋值图片地址
            this.dialogImageUrl = file.url
        },
        submit() {
            this.$refs.form.validate((val) => {
                if (val) {
                    this.form.description = this.edit.txt.html()
                    this.form.specsattr = this.form.specsattr.join(",")
                    if (this.isAdd) {
                        // console.log(this.form);
                        goodsadd(this.form).then(res => {
                            // console.log(res);
                            if (res.code == 200) {
                                this.$message('添加成功');
                                this.getGoodsList()
                                this.getCateList()
                                this.close()
                                this.getCount()
                            }
                        })


                    } else {
                        // console.log("编辑");
                        // console.log(this.form);
                        goodsedit(this.form).then(res => {
                            // console.log(res);
                            if (res.code == 200) {
                                this.$message('修改成功');
                                this.getGoodsList()
                                this.getCateList()
                                this.close()
                            }
                        })

                    }

                }
            })

        },

        // 关闭
        close() {
            this.$emit("close")
            this.reset()
        },
        // 重置
        reset() {
            this.$refs.form.resetFields()
            this.photo = []
            //销毁富文本编辑器
            this.edit.destroy()
        },
        change1(n) {
            //思路：知道当前用户选中的id值，拿id去数组中进行查找，找到所在下标，自然获得当前数组下标下的children
            let index = this.catelist.findIndex((item) => {
                return item.id == this.form.first_cateid
            })
            this.cateArr = this.catelist[index].children
            //每次切换都需要清空二级分类

            // 判断当用户点击的时候才清空
            if (n) {
                this.form.second_cateid = ""
            }
        },

        change2(n) {
            let index = this.specslist.findIndex((item) => {
                return item.id == this.form.specsid
            })
            this.specsArr = this.specslist[index].attrs
            if (n) {
                this.form.specsattr = ""

            }

        },
        lookup(id) {
            // console.log(id);
            goodsinfo({ id })
                .then(res => {
                    // console.log(res);
                    this.form = res.list
                    //图片回显
                    this.photo = this.form.img ? [{ url: this.form.img }] : []
                    this.form.id = id;
                    this.form.specsattr = this.form.specsattr.split(",")
                    this.edit.txt.html(this.form.description)
                    // console.log(this.form);
                    this.change1(false)
                    this.change2(false)

                })
        }

    },
    mounted() {
        this.getSpecsList()
        this.getCateList()
        this.getGoodsList()
        this.getCount()

        specslist().then(res => {
            // console.log(res);
            this.specslist = res.list

        })




    },
    watch: {},
    computed: {
        ...mapGetters({
            catelist: "cate/getCate",

        }),

    },
    filters: {},
    components: {}
}
</script>
<style scoped></style>